package pers.hl.module_main

import android.app.Activity
import android.os.Bundle
import android.text.TextUtils
import android.widget.EditText
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import pers.hl.common.base.BaseVBVMActivity
import pers.hl.common.base.ext.showMessage
import pers.hl.common.ui.CommonTextWatcher
import pers.hl.common.utils.MyUtils
import pers.hl.common.utils.SoftInputHelper
import pers.hl.lib_global.common.Const
import pers.hl.lib_global.model.bean.BookTag
import pers.hl.lib_global.model.bean.Library
import pers.hl.lib_global.model.bean.User
import pers.hl.module_main.common.BaseLibQuickAdapter
import pers.hl.module_main.databinding.ActivityCommonEditBinding

/**
 * 通用编辑页面
 */
class CommonEditActivity : BaseVBVMActivity<ActivityCommonEditBinding, CommonEditViewModel>() {

    private lateinit var softInputHelper: SoftInputHelper
    private var mType: Int = Int.MAX_VALUE
    private lateinit var editAdapter: EditAdapter

    private lateinit var mLibrary: Library
    private lateinit var mUser: User
    private lateinit var mBookTag: BookTag

    companion object {
        const val KEY_EDIT_TYPE = "key_edit_type"

        const val RC_LIB_MANAGE = 0x01
        const val RC_USER_MANAGE = 0x02
        const val RC_TAG_MANAGE = 0x03

        const val TYPE_LIB_MANAGE = 0x001
        const val TYPE_USER_EDIT = 0x002
        const val TYPE_TAG_EDIT = 0x003
        const val TYPE_TAG_ADD = 0x004
    }

    override fun initView(savedInstanceState: Bundle?) {
        initTitle()
        initRV()
        initOthers()
    }

    private fun initOthers() {
        softInputHelper = SoftInputHelper.attach(this).moveBy(mBinding.root)
    }

    private fun initTitle() {
        mBinding.apply {
            titleBar.ivBarLeft.setOnClickListener {
                finish()
            }
            titleBar.ivBarRight.setImageResource(R.drawable.ic_send)
            titleBar.ivBarRight.setOnClickListener {
                when (mType) {
                    TYPE_LIB_MANAGE -> {
                        LogUtils.d("提交图书馆${mLibrary}")
                        mViewModel.updateLibrary(mLibrary).observe(this@CommonEditActivity, Observer {
                            successfulBack(it)
                        })
                    }
                    TYPE_TAG_EDIT -> {
                        LogUtils.d("提交修改标签${mBookTag}")
                        mViewModel.updateTag(mBookTag).observe(this@CommonEditActivity, Observer {
                            successfulBack(it)
                        })
                    }
                    TYPE_TAG_ADD -> {
                        LogUtils.d("提交添加标签${mBookTag}")
                        mViewModel.addTag(mBookTag).observe(this@CommonEditActivity, Observer {
                            successfulBack(it)
                        })
                    }
                    TYPE_USER_EDIT -> {
                        LogUtils.d("提交编辑用户${mUser}")
                        mViewModel.updateUser(mUser).observe(this@CommonEditActivity, Observer {
                            successfulBack(it)
                        })
                    }
                }
            }
        }
    }

    private fun successfulBack(msg: String) {
        setResult(Activity.RESULT_OK, null)
        showMessage(msg)
        finish()
    }

    private fun initRV() {
        mBinding.apply {
            rvCommonEdit.layoutManager = LinearLayoutManager(this@CommonEditActivity)
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        intent?.apply {
            mType = getIntExtra(KEY_EDIT_TYPE, Int.MAX_VALUE)
            val bundle = getBundleExtra(Const.KEY.KEY_DATA_COMMON_EDIT)
            bundle?.apply {
                when (mType) {
                    TYPE_LIB_MANAGE -> {
                        setTitleText("图书馆信息编辑")
                        val data = getParcelable<Library>(Const.KEY.KEY_DATA_COMMON_EDIT)
                        mLibrary = data!!
                        showLibraryInfo(data)
                    }
                    TYPE_USER_EDIT -> {
                        setTitleText("用户信息编辑")
                        val data = getParcelable<User>(Const.KEY.KEY_DATA_COMMON_EDIT)
                        mUser = data!!
                        showUserInfo(data)
                    }
                    TYPE_TAG_EDIT -> {
                        setTitleText("书籍标签编辑")
                        val data = getParcelable<BookTag>(Const.KEY.KEY_DATA_COMMON_EDIT)
                        mBookTag = data!!
                        showTagInfo(data)
                    }
                    TYPE_TAG_ADD -> {
                        setTitleText("书籍标签添加")
                        mBookTag = BookTag(0, "", "", null)
                        showTagInfo(mBookTag)
                    }
                }
            }
        }
    }

    private fun showTagInfo(data: BookTag?) {
        data?.apply {
            editAdapter = EditAdapter(TYPE_TAG_EDIT)
            mBinding.rvCommonEdit.adapter = editAdapter
            val list = listOf(
                EditBean(1, "标签编号", id.toString(), false),
                EditBean(2, "标签名", name.toString()),
                EditBean(3, "标签描述", remark.toString())
            )
            editAdapter.addData(list)
        }
    }

    private fun showUserInfo(data: User?) {
        data?.apply {
            editAdapter = EditAdapter(TYPE_USER_EDIT)
            mBinding.rvCommonEdit.adapter = editAdapter
            val list = listOf(
                EditBean(1, "用户编号", userId.toString(), false),
                EditBean(2, "用户名", userName.toString()),
                EditBean(3, "角色", userRoleStr(), false),
                EditBean(4, "年龄", useAge.toString()),
                EditBean(5, "性别", getUserGenderStr()),
                EditBean(6, "地址", userAddr.toString()),
                EditBean(7, "电话", userTel.toString())
            )
            editAdapter.addData(list)
        }
    }

    private fun setTitleText(title: String) {
        mBinding.titleBar.tvBarTitle.text = title
    }

    private fun showLibraryInfo(data: Library?) {
        data?.apply {
            editAdapter = EditAdapter(TYPE_LIB_MANAGE)
            mBinding.rvCommonEdit.adapter = editAdapter
            val list = listOf(
                EditBean(1, "编号", libId.toString(), false),
                EditBean(2, "名称", libName.toString()),
                EditBean(3, "经度", libLongitude.toString(), false),
                EditBean(4, "纬度", libLatitude.toString(), false),
                EditBean(5, "位置", libLocation.toString())
            )
            editAdapter.addData(list)
        }
    }

    inner class EditAdapter(val type: Int) :
        BaseLibQuickAdapter<EditBean, BaseViewHolder>(R.layout.item_rv_common_edit) {

        override fun convert(holder: BaseViewHolder, item: EditBean) {
            holder.setText(R.id.tvTitle, item.title)
            holder.setText(R.id.etContent, item.content)
            holder.setEnabled(R.id.etContent, item.enable)

            val etContent = holder.getView<EditText>(R.id.etContent)
            val watcher = object : CommonTextWatcher(etContent) {
                override fun textChanged(view: EditText, text: String) {
                    when (type) {
                        TYPE_LIB_MANAGE -> {
                            when (item.tagId) {
                                2 -> mLibrary.libName = text
                                3 -> mLibrary.libLongitude = MyUtils.tryParseDouble(text, 0.0)
                                4 -> mLibrary.libLatitude = MyUtils.tryParseDouble(text, 0.0)
                                5 -> mLibrary.libLocation = text
                            }
                        }
                        TYPE_USER_EDIT -> {
                            when (item.tagId) {
                                2 -> mUser.userName = text
                                4 -> mUser.useAge = MyUtils.tryParseInt(text)
                                5 -> mUser.userGender = if (TextUtils.equals("女", text)) 2 else 1
                                6 -> mUser.userAddr = text
                                7 -> mUser.userTel = text
                            }
                        }
                        TYPE_TAG_EDIT, TYPE_TAG_ADD -> {
                            when (item.tagId) {
                                2 -> mBookTag.name = text
                                3 -> mBookTag.remark = text
                            }
                        }
                    }
                }
            }
            // 在onBindViewHolder()中通过在适当的时机添加或移除Edittext的TextChangedListener来处理数据错乱的问题。
            // 这个适当的时机就是选在Edittext获得焦点的时候添加监听器，失去焦点的时候再移除监听器，这样可以保证数据的正确性。
            etContent.setOnFocusChangeListener { v, hasFocus ->
                if (hasFocus) {
                    etContent.addTextChangedListener(watcher)
                } else {
                    etContent.removeTextChangedListener(watcher)
                }
            }
            softInputHelper.moveWith(mBinding.root, etContent)
        }
    }

    data class EditBean(
        var tagId: Int,
        var title: String,
        var content: String,
        var enable: Boolean = true
    )
}